package com.aptemo.webetek.client.commands;

import java.util.MissingResourceException;

import com.aptemo.webetek.client.Webetek;
import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.client.exceptions.WebetekLoginException;
import com.aptemo.webetek.client.exceptions.BackendException.EErrorCodes;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;

public abstract class GotAsynchCallback<T> implements AsyncCallback<T>
{

	@Override
	public void onFailure(Throwable caught)
	{
		String error = Webetek.getConstants().error() + ": ";
		try
		{
			throw caught;
		}
		catch (WebetekLoginException e)
		{
			onError(error + translate(EErrorCodes.LOGIN_ERROR.toString()), EErrorCodes.LOGIN_ERROR);
		}
		catch (BackendException e)
		{
			// do error message translation
			onError(error + translate(e.getErrorCode().toString()), e.getErrorCode());
		}
		catch (IncompatibleRemoteServiceException e)
		{
			// TODO
			onError(error + Webetek.getConstants().RPC_ERROR(), EErrorCodes.RPC_ERROR);
			//Window.Location.reload();
		}
		catch (Throwable e)
		{
			onError(error + e.getLocalizedMessage(), EErrorCodes.RPC_ERROR);
		}
	}

	private String translate(String key)
	{
		String trans = key;
		try
		{
			trans = Webetek.getConstants().getString(key);
		}
		catch (MissingResourceException mre)
		{
			mre.printStackTrace();
		}
		return trans;
	}

	public abstract void onError(String message, EErrorCodes code);
}
